let isH5 = false
// 获取用户信息
let call_type = 1;
let friendInfo = {};
let localStream;
let currentDeviceId = null;
let ice = [];
var faqifang = false; //是否发起方
let imyVideoBig = true
let isCameraOn = true
let isConnected = false
let isLoading = false
let callDuration = 0; // 记录播放时长（秒）
let timerId = null; // 定时器ID
let peerConnection = null
let iceServers = []
const audioContextBackgroundMusic = new(window.AudioContext || window.webkitAudioContext)();
const audioContextMicrophone = new(window.AudioContext || window.webkitAudioContext)();
let audioElement = new Audio('./img/call.mp3');
let audioSource = null;

function webRtcConfigFn(e) {
	let obj = base64ToObject(e)

	iceServers = [{
		urls: obj.stun
	}]
	if (obj.turn) {
		iceServers.push(obj.turn)
	}
	setwebRtcConfigFn()


}

function setwebRtcConfigFn() {
	peerConnection = new RTCPeerConnection({
		iceServers
	});
	const isUnifiedPlan = RTCPeerConnection.prototype.sdpSemantics === 'unified-plan';
	if (!isUnifiedPlan) {
		console.warn('WebRTC is not using Unified Plan, attempting to enable it.');
		peerConnection.sdpSemantics = 'unified-plan';
	}
	// 监听 ICE 候选事件
	peerConnection.onicecandidate = ({
		candidate
	}) => {
		if (candidate) {

			var wantHostMode = false;
			var wantReflexiveMode = false;
			var wantRelayMode = true; //此时此刻我们只想要后台中转模式
			var isHost = (candidate.candidate.indexOf('typ host') !== -1);
			var isSrflx = (candidate.candidate.indexOf('srflx') !== -1);
			var isRelay = (candidate.candidate.indexOf('relay') !== -1);
			var candidateType = isHost ? 'host' : (isSrflx ? 'srflx' : 'relay');

			if (wantHostMode && candidate.candidate.indexOf('typ host') == -1)
				return;

			if (wantReflexiveMode && candidate.candidate.indexOf('srflx') == -1)
				return;

			if (wantRelayMode && candidate.candidate.indexOf('relay') == -1)
				return;

			var obj = {
				cmd: "webrtc",
				user_id: friendInfo.user_id,
				type: 'ice-candidate',
				candidate: candidate
			};
			if (faqifang) {
				console.log("添加ICE包");
				ice.push(obj);
			} else {
				postMessageFn(obj)
			}
		}
	};


	// 监听远端的媒体流
	peerConnection.ontrack = (event) => {
		console.log('监听远端的媒体流', event.streams[0])

		document.getElementById('remoteVideo').querySelector('video').srcObject = event.streams[0];
		event.streams[0].getTracks().forEach(track => {
			track.onended = () => {
				// 对方已断开，做一些清理操作或提示
				console.log('远端流已停止，可能对方已断开');

			};
		});
		if (!isConnected) {
			document.getElementById('remoteVideo').querySelector('video').muted = false;
			
			setTimeout(() => {
				if (call_type == 2) {
					makeDraggable();
					videoStyleFn('videoIsShow', 1)
					remoteVideoFn()
					const userInfoElement = document.querySelectorAll(".userInfo")[0];
					userInfoElement.style.display = "none";
				}

				const answerElement = document.querySelectorAll(".answer")[0];
				const tipsElement = document.querySelectorAll(".tips")[0];
				answerElement.style.display = "none";
				tipsElement.style.display = "none";
				isConnected = true
				if (!isCameraOn && call_type == 2) {
					const localVideoElement = document.getElementById("localVideo")
					localVideoElement.querySelectorAll('.videoUserInfo')[0].classList.add(
						"displayShow");
				}
				startTimer(); // 启动定时器


			}, 500)
		}


	};

	// 监听 ICE 连接状态变化
	peerConnection.oniceconnectionstatechange = () => {
		console.log('ICE connection state: ', peerConnection.iceConnectionState);
		if (peerConnection.iceConnectionState ===
			'disconnected' || peerConnection
			.iceConnectionState === 'failed') {
			hangUpFn(1)
			// 你可以在这里做一些断开连接后的处理，例如更新 UI，提示用户等
		}
	};

	// 监听 ICE 候选状态
	peerConnection.onicegatheringstatechange = () => {
		console.log('ICE gathering state: ', peerConnection.iceGatheringState);
		if (peerConnection.iceGatheringState === 'complete') {
			console.log('ICE gathering complete 123');
		}

	};

	getUserMediaStream(); //加载本地视频
}

// 渲染用户信息
function getUserInfo(e) {
	let obj = base64ToObject(e)
	console.log(obj)
	call_type = obj.call_type
	friendInfo = obj.friendInfo
	faqifang = obj.isCaller == 1 ? true : false
	if (call_type == 2) {
		document.getElementsByClassName('flip')[0].classList.remove("hidden");
		document.getElementsByClassName('openCamera')[0].classList.remove("hidden");
		const localVideoElement = document.getElementById("localVideo")
		localVideoElement.classList.remove("hidden");


	}


	if (friendInfo.picture) {
		const userInfoImgElements = document.getElementsByClassName('userInfoImg');
		userInfoImgElements[0].src = friendInfo.picture;
		const hereImgElements = document.getElementsByClassName('hereImg');
		hereImgElements[0].src = friendInfo.picture;

	}
	if (friendInfo.nick_name) {
		const userInfoNameElements = document.getElementsByClassName('userInfoName');
		userInfoNameElements[0].innerHTML = friendInfo.nick_name;
		const hereNameElements = document.getElementsByClassName('hereName');
		hereNameElements[0].innerHTML = friendInfo.nick_name;
	}
	const tipsElements = document.getElementsByClassName('tips');
	if (faqifang) {
		const answerElement = document.querySelectorAll(".answer")[0];
		answerElement.style.display = "none";
		tipsElements[0].innerHTML = "等待对方接受邀请";
	} else {
		tipsElements[0].innerHTML = "邀请你接受" + (call_type == 1 ? '语音' : '视频') + "通话";
	}



}
// 渲染我的信息
function getMyUserInfo(e) {
	let obj = base64ToObject(e)
	if (obj.picture) {
		const myImgElements = document.getElementsByClassName('myImg');
		myImgElements[0].src = obj.picture;
	}
	if (obj.nick_name) {
		const myNameElements = document.getElementsByClassName('myName');
		myNameElements[0].innerHTML = obj.nick_name;
	}




}

// 挂断
function hangUpFn(hangUpType) {
	stopTimer()
	stopBackgroundMusic()
	try {
		// 停止本地媒体流
		if (localStream) {
			localStream.getTracks().forEach(track => track.stop());
			document.getElementById('localVideo').srcObject = null;
			localStream = null; // 清除引用
		}
		// 停止远程媒体流
		const remoteVideoDom = document.getElementById('remoteVideo');
		if (remoteVideoDom && remoteVideoDom.srcObject) {
			const remoteStream = remoteVideoDom.srcObject;
			remoteStream.getTracks().forEach(track => track.stop());
			remoteVideoDom.srcObject = null;
		}
		// 清理 peerConnection 相关事件
		if (peerConnection) {
			// 解除 ICE 候选和媒体流的监听
			peerConnection.onicecandidate = null;
			peerConnection.ontrack = null;
			// 关闭连接并释放资源
			peerConnection.close();
			peerConnection = null; // 置空引用
		}

	} catch (error) {

	}
	console.log('WebRTC 连接已关闭 this.callDuration--', callDuration);
	postMessageFn({
		type: 'quit',
		text: formattedTime(callDuration),
		callDuration,
		hangUpType

	})

}
// 传递数据到父级
function postMessageFn(obj) {
	console.log('传递数据到父级--', obj)
	if (isH5) {
		window.parent.postMessage(objectToBase64(obj), '*');
	} else {
		uni.postMessage({
			data: objectToBase64(obj)
		});
	}
}
// 接收并设置远端的 ICE 候选
function handleICECandidate(Content) {
	let obj = base64ToObject(Content)
	let candidate = obj.candidate
	console.log('接收并设置远端的 ICE 候选', candidate)
	var wantHostMode = false;
	var wantReflexiveMode = false;
	var wantRelayMode = true; //此时此刻我们只想要后台中转模式
	var isHost = (candidate.candidate.indexOf('typ host') !== -1);
	var isSrflx = (candidate.candidate.indexOf('srflx') !== -1);
	var isRelay = (candidate.candidate.indexOf('relay') !== -1);
	var candidateType = isHost ? 'host' : (isSrflx ? 'srflx' : 'relay');

	if (wantHostMode && candidate.candidate.indexOf('typ host') == -1)
		return;

	if (wantReflexiveMode && candidate.candidate.indexOf('srflx') == -1)
		return;

	if (wantRelayMode && candidate.candidate.indexOf('relay') == -1)
		return;
	console.log("收到ICE包123", candidate);
	peerConnection.addIceCandidate(new RTCIceCandidate(candidate)).catch(error => {
		console.error('添加 ICE 候选失败1', error);
		console.error('添加 ICE 候选失败2', candidate);

	}).then(() => {
		console.log('添加 ICE 候选成功', candidate);

	});
};
let isMicrophoneOn = true
let deviceId = null
let facingMode = "user"
//加载本地视频
// "user"：前置摄像头
// "environment"：后置摄像头
// "left"：左侧摄像头
// "right"：右侧摄像头

// 播放背景音乐的函数
function playBackgroundMusic() {
	audioElement.loop = true;
	audioSource = audioContextBackgroundMusic.createMediaElementSource(audioElement);
	audioSource.connect(audioContextBackgroundMusic.destination);

	audioElement.play().catch((err) => {
		console.error("播放背景音乐失败:", err);
	});
}

async function getUserMediaStream() {
	try {

		let constraints = {
			audio: true
		}
		constraints['video'] = deviceId ? {
			deviceId: {
				exact: deviceId
			}
		} : {
			facingMode
		}
		console.log(constraints)
		var stream = await navigator.mediaDevices.getUserMedia(constraints);
		playBackgroundMusic()
		const videoElement = document.getElementById('localVideo').querySelector('video');
		videoElement.srcObject = stream;
		videoElement.muted = true;
		// 添加播放控制
		videoElement.play().catch(error => {
			console.log('需要用户交互后才能播放');
			// 可以在这里显示提示让用户点击界面
		});
		const microphoneSource = audioContextMicrophone.createMediaStreamSource(stream);

		stream.getTracks().forEach(track => peerConnection.addTrack(track, stream)); // 将本地流添加到 peerConnection
		localStream = stream;

		var obj = {
			type: "localAudioCompleted"
		};
		postMessageFn(obj)


		setTimeout(() => {
			isLoading = true
		}, 500)




	} catch (error) {
		alert('获取媒体失败');
		hangUpFn(1)
		console.log('Error accessing media devices.', error);
	}
};


// 停止背景音乐的函数
function stopBackgroundMusic() {
	if (audioElement) {
		audioElement.pause(); // 停止背景音乐
		audioElement.currentTime = 0; // 重置到音频开始位置
		console.log("背景音乐已停止");
	}
}

async function createOffer() {
	try {
		// 确保 PeerConnection 已正确配置并且有轨道
		const offer = await peerConnection.createOffer();

		// 删除 'a=extmap-allow-mixed' 这一行
		offer.sdp = offer.sdp.replace(/^a=extmap-allow-mixed\r?\n/gm, '');

		// 检查 offer 是否完整
		if (!isOfferComplete(offer.sdp)) {
			console.error("Offer 不完整，重新生成...");
			setTimeout(() => {
				Call();
			}, 500);
			return;
		}

		// 设置本地描述
		await peerConnection.setLocalDescription(offer);
		console.log('本地描述已设置', offer);

		return offer;
	} catch (error) {
		console.error('创建 Offer 时发生错误: ', error);
		return null;
	}
}


// 获取对方推送的offer
let handleOfferOffer = {}

function getOfferFn(Content) {
	let obj = base64ToObject(Content)
	console.log('获取对方推送的offer2--', obj)

	handleOfferOffer = obj.offer


}
// 收到用户接听应答
function answerFn(Content) {
	let obj = base64ToObject(Content)
	console.log('收到用户接听应答---', obj)
	peerConnection.setRemoteDescription(new RTCSessionDescription(obj.answer));
	console.log("准备发送ICE包", ice);

	for (var i = 0; i < ice.length; i++) {
		console.log('ice[i]--', ice[i])
		postMessageFn(ice[i])
	}
	stopBackgroundMusic()
}
// 接听电话
async function handleOffer() {
	const answerElement = document.querySelectorAll(".answer")[0];
	const imgElement = answerElement.querySelector("img");
	imgElement.src = "./img/loading.gif";
	if (!isLoading) {
		console.log('本地流还未加载好11');
		setTimeout(() => {
			handleOffer()
		}, 500)
		return;
	}

	try {
		console.log('handleOfferOffer--', handleOfferOffer)
		await peerConnection.setRemoteDescription(new RTCSessionDescription(handleOfferOffer));
		const answer = await peerConnection.createAnswer();
		await peerConnection.setLocalDescription(answer);
		var obj = {
			cmd: "webrtc",
			user_id: friendInfo.user_id,
			call_type: call_type,
			type: 'answer',
			answer: answer
		};
		postMessageFn(obj)
		stopBackgroundMusic()
	} catch (error) {
		var obj = {
			type: 'getOffer'
		};
		postMessageFn(obj)
		setTimeout(() => {
			console.log('重新接听')
			handleOffer()
		}, 500)
	}
}
async function Call() {

	var offer = await createOffer();
	console.log('创建 Offer--', offer)
	if (offer == null) {

		return;
	}
	var par = {
		cmd: "webrtc",
		user_id: friendInfo.user_id,
		type: 'offer',
		call_type: call_type,
		offer: offer
	};

	console.log("发送呼叫请求", par);
	postMessageFn(par)
	ice = []; //ICE包置为空
	faqifang = true;
	console.log("清空ICE包");
}


document.addEventListener('UniAppJSBridgeReady', function() {
	uni.getEnv(function(res) {
		res.h5 = res.h5 ? true : false
		postMessageFn({
			type: 'getUserInfo'
		})
	})
})
let isSwitching = false;

// 翻转摄像头
function switchCameraFn() {
	if (isSwitching) {
		console.log('摄像头切换操作正在进行中，请稍后...');
		return;
	}

	const localVideoElement = document.getElementById("localVideo");
	isSwitching = true;

	// 获取当前的视频轨道
	const videoTrack = localStream.getVideoTracks()[0];

	// 停止当前的视频轨道，释放资源
	videoTrack.stop();

	// 获取设备列表
	navigator.mediaDevices.enumerateDevices().then(devices => {
		const videoDevices = devices.filter(device => device.kind === 'videoinput');

		if (videoDevices.length <= 1) {
			console.log('没有多个摄像头可供切换');
			isSwitching = false; // 重置标记
			return;
		}

		// 查找当前设备在设备列表中的位置
		const currentDeviceIndex = videoDevices.findIndex(device =>
			device.deviceId === videoTrack.getSettings().deviceId
		);
		const nextDeviceIndex = (currentDeviceIndex + 1) % videoDevices.length;
		const nextDeviceId = videoDevices[nextDeviceIndex].deviceId;

		console.log('切换到摄像头:', nextDeviceId);

		// 获取新的媒体流，保持麦克风的状态
		navigator.mediaDevices.getUserMedia({
			video: {
				deviceId: nextDeviceId
			},
			audio: isMicrophoneOn
		}).then(stream => {
			const videoElement = document.getElementById('localVideo').querySelector('video');
			videoElement.muted = true;
			videoElement.srcObject = stream;
			localStream = stream;

			// 强制触发播放
			videoElement.play().catch(error => {
				console.log('自动播放被阻止，需要用户交互');
			});

			// 获取新的视频轨道和设备信息
			const newVideoTrack = stream.getVideoTracks()[0];
			const device = newVideoTrack.getSettings();
			currentDeviceId = device.deviceId;

			if (RTCPeerConnection.prototype.getSenders && typeof RTCRtpSender.prototype.replaceTrack ===
				'function') {
				// 支持 replaceTrack，直接替换视频轨道
				peerConnection.getSenders().forEach(sender => {
					if (sender.track && sender.track.kind === 'video') {
						sender.replaceTrack(newVideoTrack);
					}
				});
			} else {
				// 不支持 replaceTrack，使用兼容方案
				console.warn('浏览器不支持 replaceTrack，使用兼容方案切换摄像头');

				// 停止并移除当前的视频轨道
				peerConnection.getSenders().forEach(sender => {
					if (sender.track && sender.track.kind === 'video') {
						sender.track.stop();
						peerConnection.removeTrack(sender);
					}
				});

				// 重新添加新的视频轨道
				const newVideoTrack = stream.getVideoTracks()[0];
				const newSender = peerConnection.addTrack(newVideoTrack, stream);
				console.log('手动添加新的视频轨道:', newSender);

				// 确保音频轨道保持原有状态
				const audioTrack = stream.getAudioTracks()[0];
				if (audioTrack) {
					// 确保音频轨道启用
					audioTrack.enabled = isMicrophoneOn;

					// 移除旧的音频轨道并添加新的音频轨道
					peerConnection.getSenders().forEach(sender => {
						if (sender.track.kind === 'audio') {
							// 停止并移除音频轨道
							sender.track.stop();
							peerConnection.removeTrack(sender);
						}
					});

					// 重新添加音频轨道
					peerConnection.addTrack(audioTrack, stream);
					console.log('音频轨道已替换并启用');
				} else {
					console.log('没有音频轨道');
				}

				// 重新创建 Offer 并发送给远端
				createOfferAndSend();
			}

			// 确保音频轨道保持原有状态
			const audioTrack = stream.getAudioTracks()[0];
			if (audioTrack) {
				audioTrack.enabled = isMicrophoneOn;
				console.log('isMicrophoneOn--', isMicrophoneOn)
			} else {
				console.log('没有音频轨道');
			}

			// 重置标记
			setTimeout(() => {
				isSwitching = false;
			}, 1000);
		}).catch(error => {
			console.error('getUserMedia 失败:', error);
			if (error.name === 'NotFoundError') {
				console.error('没有找到合适的摄像头设备');
			} else if (error.name === 'NotAllowedError') {
				console.error('用户拒绝了权限请求');
			} else {
				console.error('其他错误', error);
			}
			isSwitching = false; // 发生错误时重置标记
		});
	}).catch(error => {
		console.error('获取设备列表失败', error);
		isSwitching = false; // 发生错误时重置标记
	});
}

// 需要补充的创建 Offer 函数
async function createOfferAndSend() {

	var offer = await createOffer();
	console.log('创建 Offer--222', offer)
	if (offer == null) {
		return;
	}
	var par = {
		cmd: "webrtc",
		user_id: friendInfo.user_id,
		type: 'push',
		call_type: call_type,
		content: {
			offer: offer,
			type: "offers_witchCamera"


		}
	};

	console.log("发送呼叫请求2", par);
	postMessageFn(par)



}
// 切换摄像头的开启和关闭
function toggleCameraFn() {
	const cameraIcon = document.getElementById("cameraIcon");
	const cameraStatus = document.getElementById("cameraStatus");
	const localVideoElement = document.getElementById("localVideo")

	if (isCameraOn) {
		// 关闭摄像头
		if (localStream) {
			// 暂停视频轨道而非完全停止
			localStream.getTracks().forEach(track => track.enabled = false);
		}

		// 更新UI
		cameraIcon.src = "./img/closeCamera.png";
		cameraStatus.textContent = "摄像头已关";
		localVideoElement.querySelector('video').classList.add("hidden");
		if (isConnected) {
			localVideoElement.querySelectorAll('.videoUserInfo')[0].classList.add("displayShow");
		}


	} else {
		// 开启摄像头
		if (localStream) {
			// 恢复视频轨道
			localStream.getTracks().forEach(track => track.enabled = true);
		} else {
			startCamera();
		}

		// 更新UI
		cameraIcon.src = "./img/openCamera.png";
		cameraStatus.textContent = "摄像头已开";
		localVideoElement.querySelector('video').classList.remove("hidden");
		localVideoElement.querySelectorAll('.videoUserInfo')[0].classList.remove("displayShow");
	}

	// 切换摄像头状态
	isCameraOn = !isCameraOn;


	var obj = {
		type: 'push',
		content: {
			type: "isCameraOn",
			isCameraOn


		}
	};
	postMessageFn(obj)
}
// 开启摄像头
async function startCamera() {
	try {
		// 请求用户的媒体设备（视频）
		localStream = await navigator.mediaDevices.getUserMedia({
			video: true
		});

		// 设置视频流到 video 元素
		const videoElement = document.getElementById("localVideo").querySelector('video');
		videoElement.srcObject = localStream;
	} catch (error) {
		console.error('获取摄像头失败:', error);
	}
}
// 切换麦克风的开启和关闭
function toggleMicrophone() {
	if (!localStream) {
		console.log('本地流未初始化');
		return;
	}

	// 获取音频轨道
	const audioTrack = localStream.getAudioTracks()[0];
	const imgElement = document.getElementById("microphoneIcon");
	const statusElement = document.getElementById("microphoneStatus");
	// 判断音频轨道是否存在
	if (audioTrack) {
		// 切换音频轨道的 enabled 属性
		audioTrack.enabled = !audioTrack.enabled;
		isMicrophoneOn = audioTrack.enabled;

		// 根据麦克风的状态进行相应的处理
		if (audioTrack.enabled) {
			console.log('麦克风已开启');
			imgElement.src = "./img/openMicrophone.png";
			statusElement.textContent = "麦克风已开";

		} else {
			console.log('麦克风已关闭');
			imgElement.src = "./img/closeMicrophone.png";
			statusElement.textContent = "麦克风已关";
		}


		// 更新远程音频流（通过设置 audioTrack.enabled 影响远程音频的接收）
		updateRemoteAudioTrackState(audioTrack.enabled);
	} else {
		console.log('未找到音频轨道');
		// 如果没有音频轨道，可以尝试重新初始化流
		reinitializeStream();
	}
}
// 更新远程音频轨道的状态
function updateRemoteAudioTrackState(isEnabled) {
	// 更新 peerConnection 的音频轨道状态
	peerConnection.getSenders().forEach(sender => {
		if (sender.track && sender.track.kind === 'audio') {
			sender.track.enabled = isEnabled;
		}
	});
}
// 重新初始化音频流
function reinitializeStream() {
	console.log('重新初始化音频流...');
	navigator.mediaDevices.getUserMedia({
			audio: true
		})
		.then(stream => {
			// 更新本地流
			localStream = stream;
			// 绑定音频轨道
			const audioTrack = localStream.getAudioTracks()[0];
			if (audioTrack) {
				// 将新的音频轨道的 enabled 属性设置为初始状态
				audioTrack.enabled = isMicrophoneOn;
				console.log('重新获取并启用音频轨道');
			}
		})
		.catch(error => {
			console.error('重新获取音频流失败', error);
		});
}
// 放大本地视频
function localVideoFn() {
	let remoteVideoElement = document.getElementById("remoteVideo");
	let localVideoElement = document.getElementById("localVideo");
	if (!imyVideoBig) {
		imyVideoBig = true
		remoteVideoElement.classList.add("smallVideo");
		remoteVideoElement.classList.remove("bigVideo");

		localVideoElement.classList.add("bigVideo");
		localVideoElement.classList.remove("smallVideo");
	}
}
// 放大远端视频
function remoteVideoFn() {
	let remoteVideoElement = document.getElementById("remoteVideo");
	let localVideoElement = document.getElementById("localVideo");
	if (imyVideoBig) {
		imyVideoBig = false
		remoteVideoElement.classList.add("bigVideo");
		remoteVideoElement.classList.remove("smallVideo");
		localVideoElement.classList.add("smallVideo");
		localVideoElement.classList.remove("bigVideo");
	}
}


// 自定义消息
async function customMessageFn(Content) {
	let obj = base64ToObject(Content)
	if (obj.content) {
		// 对方摄像头
		if (obj.content.type == "isCameraOn") {
			const remoteVideoElement = document.getElementById("remoteVideo")
			if (obj.content.isCameraOn) {
				// 开
				remoteVideoElement.querySelector('video').classList.remove("hidden");
				remoteVideoElement.querySelectorAll('.videoUserInfo')[0].classList.remove("displayShow");
			} else {
				// 关
				remoteVideoElement.querySelector('video').classList.add("hidden");
				remoteVideoElement.querySelectorAll('.videoUserInfo')[0].classList.add("displayShow");
			}


		}
		// 退出
		if (obj.content.type == "quit") {
			if (obj.content && obj.content.callDuration) {
				callDuration = obj.content.callDuration
			}
			hangUpFn(2)
		}
		// 翻转摄像头
		if (obj.content.type == "offers_witchCamera") {

			console.log('翻转摄像头', obj.content.offer)
			handleOfferOffer = obj.content.offer
			handleOffer()



		}




	}

}

function videoStyleFn(type, status) {
	if (type == 'videoIsShow') {
		let remoteVideoElement = document.getElementById("remoteVideo");
		if (status) {
			remoteVideoElement.classList.remove("hidden"); // 显示元素
		} else {
			remoteVideoElement.classList.add("hidden"); // 隐藏元素
		}
	}


}
// 将对象转换为 Base64 字符串
function objectToBase64(obj) {
	let jsonString = JSON.stringify(obj);
	const base64String = btoa(unescape(encodeURIComponent(jsonString)));
	return base64String;
}
// 将 Base64 转回对象
function base64ToObject(base64String) {
	const jsonString = decodeURIComponent(escape(atob(base64String)));

	const obj = JSON.parse(jsonString);

	return obj;
}
// 拖拽
function makeDraggable() {
	const elements = document.querySelectorAll('.smallVideo');

	elements.forEach(element => {
		let offsetX, offsetY, isDragging = false;

		// 获取窗口的宽度和高度
		const windowWidth = window.innerWidth;
		const windowHeight = window.innerHeight;

		// 触摸开始事件
		element.addEventListener('touchstart', function(e) {
			isDragging = true;

			// 获取触摸点相对元素的偏移
			offsetX = e.touches[0].clientX - element.getBoundingClientRect().left;
			offsetY = e.touches[0].clientY - element.getBoundingClientRect().top;
		});

		// 触摸移动事件
		document.addEventListener('touchmove', function(e) {
			if (isDragging) {
				// 计算触摸点的位置
				let left = e.touches[0].clientX - offsetX;
				let top = e.touches[0].clientY - offsetY;

				// 限制元素不超出窗口左边、右边、上边、下边的边界
				left = Math.max(0, Math.min(left, windowWidth - element.offsetWidth));
				top = Math.max(0, Math.min(top, windowHeight - element.offsetHeight));

				// 更新元素位置
				element.style.left = `${left}px`;
				element.style.top = `${top}px`;
			}
		});

		// 触摸结束事件
		document.addEventListener('touchend', function() {
			isDragging = false;
		});
	});
}
// 开始定时更新播放时长
function startTimer() {
	if (timerId) return; // 如果定时器已经启动，则不再重复启动
	const callDurationElement = document.querySelector('.callDuration');
	// 每秒更新一次播放时长
	timerId = setInterval(() => {
		callDuration++;
		callDurationElement.textContent = formattedTime(callDuration);
	}, 1000);
}
// 停止定时更新播放时长
function stopTimer() {
	if (timerId) {
		clearInterval(timerId); // 停止定时器
		timerId = null; // 清空定时器ID
	}
}
// 格式化播放时长
function formattedTime(callDuration) {
	const minutes = String(Math.floor(callDuration / 60)).padStart(2, '0');
	const seconds = String(callDuration % 60).padStart(2, '0');
	return `${minutes}:${seconds}`;
}
// 判断 SDP 是否完整
function isOfferComplete(sdp) {
	// 检查 SDP 中的关键字段是否存在
	const requiredFields = ['v=', 'o=', 's=', 't=', 'a=', 'm='];
	return requiredFields.every(field => sdp.includes(field));
}